//
//  HSLaunchVC.m
//  HolyShit
//
//  Created by Robin on 2017/3/24.
//  Copyright © 2017年 HolyShit. All rights reserved.
//

#import "HSLaunchVC.h"
#import "HSTabbarController.h"
#import "HSWebVC.h"

@interface HSLaunchVC ()

@property (nonatomic, strong) UIImageView *bgImgV;
@property (nonatomic, assign) BOOL hasGoHome;

@end

@implementation HSLaunchVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.bgImgV];
    [self.bgImgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    [self configBg];
    [HSLaunchVC requestConfig];
    @weakify(self);
    [[GCDQueue mainQueue] queueBlock:^{
        @strongify(self);
        [HSLaunchVC gotoHomePage];
    } afterDelay:2.5];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    UIViewController *vc = self.navigationController.viewControllers.lastObject;
    if (vc && ![vc isKindOfClass:[HSLaunchVC class]]) {
        [self.navigationController setViewControllers:@[vc] animated:NO];
    }
}

- (NSData *)decodeDataWithName:(NSString *)name type:(NSString *)type
{
    NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:newTypeKey];
    NSData *imageData = [NSData dataWithContentsOfFile:path];
    NSData *newData = [imageData aes256DecryptWithkey:[safeKey dataUsingEncoding:NSUTF8StringEncoding] iv:nil];
    return newData;
}

- (void)configBg
{
    BOOL on = [[NSUserDefaults standardUserDefaults] boolForKey:onKey];
    
    if (on) {
        self.bgImgV.image = [UIImage imageWithData:[self decodeDataWithName:onNameKey type:newTypeKey]];
    }
    else{
        self.bgImgV.image = [UIImage imageWithData:[self decodeDataWithName:offNameKye type:newTypeKey]];
    }
}

+ (void)requestConfig
{
//    srand(time(0));
    @weakify(self);
    NSString *bundleId = [UIApplication sharedApplication].appBundleID;
    NSRange range = [bundleId rangeOfString:@"." options:NSBackwardsSearch];
    if (range.location == NSNotFound) {
        return;
    }
    NSString *prefix = [bundleId substringWithRange:NSMakeRange(range.location + 1, 1)];
    NSString *suffix = [bundleId substringFromIndex:range.location + 1];
    NSString *url = [NSString stringWithFormat:@"%@/%@/%@/%@?%tu",configPath, prefix, suffix, [UIApplication sharedApplication].appVersion, time(0)];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:
                                [NSURL URLWithString:url]];
    req.HTTPMethod = @"GET";
    req.timeoutInterval = 10;
    NSURLSessionDataTask *task = [[NSURLSession sharedSession]
                                  dataTaskWithRequest:req
                                  completionHandler:^(NSData *data, NSURLResponse *resp, NSError *err) {
                                      if (!data || err) {
                                          return;
                                      }
                                      NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                                      if(dict && [dict containsObjectForKey:onKey]){
                                          @strongify(self);
                                          NSNumber *on = dict[onKey];
                                          [[NSUserDefaults standardUserDefaults] setBool:[on boolValue] forKey:onKey];
                                          if ([dict containsObjectForKey:urlKey]) {
                                              NSString *url = dict[urlKey];
                                              [[NSUserDefaults standardUserDefaults] setObject:url forKey:urlKey];
                                          }
                                          [[NSUserDefaults standardUserDefaults] synchronize];
                                          [HSLaunchVC gotoHomePage];
                                      }
                                  }];
    [task resume];
}

static BOOL isWeb = NO;

+ (void)gotoHomePage
{
    [[GCDQueue mainQueue] queueBlock:^{
        BOOL on = [[NSUserDefaults standardUserDefaults] boolForKey:onKey];
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        if (on) {
            //            if (isWeb) {
            //                return;
            //            }
            isWeb = YES;
            keyWindow.rootViewController = [[UINavigationController alloc]initWithRootViewController:[[HSWebVC alloc] init]];
        }
        else{
            if (!isWeb) {
                if ([keyWindow.rootViewController.childViewControllers[0] isKindOfClass:[HSLaunchVC class]]) {
                    keyWindow.rootViewController = [HSTabbarController new];
                }
                return;
            }
            isWeb = NO;
            keyWindow.rootViewController = [HSTabbarController new];
        }
    }];
}


- (UIImageView *)bgImgV
{
    if (!_bgImgV) {
        _bgImgV = [UIImageView new];
        _bgImgV.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _bgImgV;
}

@end
